package top.jacktgq.asynchronized;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author CandyWall
 * @Date 2022/3/15--17:46
 * @Description
 */
@Slf4j
public class CompletableFutureExample {
    @Test
    public void test1() throws ExecutionException, InterruptedException {
        /*ExecutorService ex = Executors.newFixedThreadPool(10);
        Future<Boolean> future = ex.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return true;
        });
        if (future.get()) {
            System.out.println("Done");
        }*/

        CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).whenComplete((v, t) -> System.out.println("Done"));

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    private int get() {
        int value = ThreadLocalRandom.current().nextInt(20);
        System.out.println(Thread.currentThread().getName() + " will be sleep " + value);
        try {
            TimeUnit.SECONDS.sleep(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " execute done " + value);
        return value;
    }

    private static void display(int data) {
        System.out.println("Display " + data);
    }

    @Test
    public void test2() throws InterruptedException {
        /*ExecutorService executorService = Executors.newFixedThreadPool(10);

        List<Callable<Integer>> tasks = IntStream.range(0, 10).boxed().map(i -> (Callable<Integer>) () -> get()).collect(Collectors.toList());

        executorService.invokeAll(tasks).stream().map(future -> {
            try {
                return future.get();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
        }).parallel().forEach(CompletableFutureExample::display);*/
        IntStream.range(0, 10).boxed().forEach(i -> CompletableFuture.supplyAsync(new CompletableFutureExample()::get).thenAccept(CompletableFutureExample::display).whenComplete((v, t) -> System.out.println("Done")));

        Thread.currentThread().join();
    }
}
